<template>
  <div class="app-container">
    <el-card>
      <!--用户数据-->
      <el-form :model="queryParams" ref="queryForm" size="small" label-width="100px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="题目内容">
              <el-input v-model.trim="queryParams.questionContent" placeholder="输入内容" clearable @input="handleQuery"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实践课程" prop="practiceType">
              <el-select v-model="queryParams.practiceType" placeholder="请选择" clearable @change="handleQuery">
                <el-option v-for="item in practiceTypeList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="题目类型">
              <el-select v-model="queryParams.type" placeholder="请选择" clearable @change="handleQuery">
                <el-option v-for="item in taskStatusList" :key="item.id" :label="item.type" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">
              <el-date-picker v-model="dateRangeQuery" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                @change="handleQuery" style="width: 100%" start-placeholder="开始日期"
                end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人">
              <el-input v-model.trim="queryParams.createUserName" placeholder="输入内容" clearable @input="handleQuery"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <!-- <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button> -->
              <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" v-hasPermi="['project:bank:add']" plain icon="el-icon-plus" size="mini"
            @click="uploadOpen = true">导入试题</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['project:bank:add']"
            @click="addBankBtn">新增试题</el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="tableList">
        <el-table-column type="index" width="50" align="center" />
        <el-table-column label="题目内容" align="center" prop="questionContent" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div v-html="scope.row.questionContent"></div>
          </template>
        </el-table-column>
        <el-table-column label="实践课程" align="center">
          <template slot-scope="scope">
            {{ practiceTypeList.find(v => v.id == scope.row.practiceType).name }}
          </template>
        </el-table-column>
        <el-table-column label="题目类型" align="center" key="status">
          <template slot-scope="scope">
            {{ taskStatusList.find(v => v.id == scope.row.type).type }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" key="createTime">
          <template slot-scope="scope">
            {{ (scope.row || '').createTime.slice(0, 16) }}
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" key="createUserName" prop="createUserName">
          <template slot-scope="scope">
            {{ scope.row.createUserName }} {{ scope.row.jsNumber ? '(' + scope.row.jsNumber + ')' : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" @click="previewBank(scope.row)" v-hasPermi="['project:bank:preview']">预览</el-button>
            <el-button type="text" @click="updateBank(scope.row)" v-hasPermi="['project:bank:edit']">编辑</el-button>
            <el-button style="color: #f56c6c;" type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['project:bank:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />

      <!--  -->
      <el-dialog title="导入试题" :visible.sync="uploadOpen" width="420px">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" class="demo-ruleForm">
          <el-form-item label="格式类型:" prop="region">
            <el-select v-model="ruleForm.region" placeholder="请选择格式类型" @change="changeRegion">
              <el-option label="Exel" value="Exel"></el-option>
              <el-option label="Word" value="Word"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="实践课程:" prop="practiceType">
            <el-select v-model="ruleForm.practiceType" placeholder="请选择">
              <el-option v-for="item in practiceTypeList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-upload ref="upload" action="" :limit="1" :accept="flieType" :on-change="fileChange" :auto-upload="false"
          :file-list="fileList" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span v-if="ruleForm.region == 'Exel'">仅允许导入xlsx格式文件。</span>
            <span v-else>仅允许导入docx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm" v-hasPermi="['project:bank:add']">确 定</el-button>
          <el-button @click="uploadOpen = false">取 消</el-button>
        </div>
      </el-dialog>


      <el-dialog title="导入错误" :visible.sync="errorOpen" width="500px">
        <el-table :data="errorData">
          <el-table-column property="message" label="错误详情"></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="errorOpen = false">确 定</el-button>
        </div>
      </el-dialog>


      <el-dialog title="预览" width="60%" :visible.sync="open" append-to-body class="dialogClass">
        <el-row>
          <el-card>
            <el-col :span="24" style="margin-bottom: 10px;">
              <div class="inforClass">试题</div>
            </el-col>
            <el-col :span="24">
              <div style="display: flex; font-weight: 600;align-items: center;">
                <div style="margin: 0 8px;">[{{ bankInfo.type == 1 ? '单选题' : bankInfo.type == 2 ? '判断题' : '多选题' }}]</div>
                <div v-html="bankInfo.questionContent"></div>
              </div>
              <div v-for="it in bankInfo.questionBankOptionList" :key="it.name" class="bankLabelStyle">
                <el-checkbox v-model="it.answer" :label="it.name" style="display: block;"
                  class="non-clickable-checkbox" />
                <span> {{ bankInfo.name }}. </span>
                <div style="flex: 1" v-html="it.content"></div>
              </div>
              <div>
                <el-form>
                  <el-form-item label="答案解析:">
                    <div v-html="bankInfo.answerAnalysis || '暂无解析'"></div>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-card>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="open = false">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { typeCongfigList } from "@/api/semesManage";
import { listPaper, delePaper, excelImport, wordImport, detailPaper } from "@/api/paperInterlocu/paper";
export default {
  name: "bankManage",
  data() {
    return {
      errorOpen: false, // 错误提示框
      errorData: [], // 错误数据
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      uploadOpen: false,
      open: false, // 预览窗口
      dateRangeQuery: [], // 查询
      tableList: [],
      // 弹出层标题
      taskStatusList: [{ id: 1, type: '单选题' }, { id: 2, type: '判断题' }, { id: 3, type: '多选题' }], // 任务状态
      practiceTypeList: [], // 实践课程
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        questionContent: undefined,
        status: undefined,
        practiceType: undefined
      },
      updateSupport: '',
      ruleForm: {
        region: 'Exel',
        practiceType: '',
      },
      fileList: [], // 上传文件
      rules: {
        region: [
          { required: true, message: "请选择导入格式", trigger: "blur" },
        ],
        practiceType: [
          { required: true, message: "请选择实践课程", trigger: "blur" },
        ],
      },
      flieType: '.xlsx, .xls',
      bankInfo: {},
      optionList: []
    };
  },
  watch: {
    uploadOpen: {
      handler(newVal, oldVal) {
        this.fileList = [];
        this.ruleForm = {
          region: 'Exel',
          practiceType: '',
        };
      }
    }
  },
  created() {
    // const permissList = sessionStorage.getItem('practiceTypes').split(',');
    // const typeMap = {
    //   1: { type: '劳动教育', id: 1 },
    //   2: { type: '职业素养', id: 2 },
    //   3: { type: '应急安全', id: 3 },
    //   4: { type: '思政实践', id: 4 },
    //   5: { type: '创新创业', id: 5 }
    // };

    // permissList.forEach(v => {
    //   if (typeMap[v]) {
    //     this.practiceTypeList.push(typeMap[v]);
    //   }
    // });
    this.getTypeCongfigList();
    this.getList();
  },
  methods: {
    getTypeCongfigList() {
      typeCongfigList({
        pageNum: 1,
        pageSize: 50,
      }).then(res => {
        this.practiceTypeList = res.rows;
      });
    },
    /** 查询列表 */
    getList() {
      const time = this.dateRangeQuery && this.dateRangeQuery.length > 0 ? { startTime: this.dateRangeQuery[0] + ' 00:00:00', endTime: this.dateRangeQuery[1] + ' 23:59:59' } : {};
      listPaper({ ...this.queryParams, ...time }).then(res => {
        if (res.code === 200) {
          this.tableList = res.rows;
          this.total = res.total;
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeQuery = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        questionContent: undefined,
        status: undefined,
        practiceType: undefined
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    changeRegion() {
      this.flieType = this.ruleForm.region == "Exel" ? ".xlsx" : ".docx";
      this.fileList = [];
    },
    /** 下载模板操作 */
    importTemplate() {
      if (this.ruleForm.region == "Exel") {
        this.download(
          "project/paper/downloadExcel",
          {},
          `Excel试题导入模板.xlsx`,
        );
      } else {
        this.download(
          "project/paper/downloadWord",
          {},
          `Word试题导入模板.docx`,
        );
      }
    },
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    submitFileForm() {
      if (this.fileList.length === 0) {
        this.$message.warning('请选择文件！')
        return
      }
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          const formData = new FormData();
          formData.append('file', this.fileList[0].raw);
          formData.append('practiceType', this.ruleForm.practiceType);
          const urlName = this.ruleForm.region == "Exel" ? excelImport : wordImport;

          urlName(formData).then((res) => {
            if (res.code === 200) {
              if (res.data.successNumber > 0) {
                this.$message.success(`导入${res.data.successNumber}道试题成功!`)
              }
              if (res.data.errorMessage.length == 0) {
                this.uploadOpen = false;
              } else {
                this.errorData = res.data.errorMessage;
                this.uploadOpen = false;
                this.errorOpen = true;
              }
              this.getList();
            }
          })
        };
      });
    },
    // 新增
    addBankBtn() {
      this.$router.push({ path: "/addBank", meta: { title: '新增试题' } })
    },
    // 编辑
    updateBank(row) {
      this.$router.push({ path: "/addBank", query: { id: row.id }, meta: { title: '编辑试题' } })
    },
    // 预览
    previewBank(row) {
      this.open = true;
      this.bankInfo = {};
      this.getBankDetail(row.id);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(`是否确认删除"${row.questionContent}"题目内容的数据项？`, '确定删除', { dangerouslyUseHTMLString: true, customClass: 'my-custom-confirm' })
        .then(function () {
          return delePaper(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },

    // 预览
    getBankDetail(id) {
      detailPaper(id).then(res => {
        if (res.code == 200) {
          this.bankInfo = res.data;
          this.bankInfo.questionBankOptionList.forEach(item => {
            item.answer = item.answer == 1 ? true : false
          });
        }
      })
    },
  },
};
</script>
<style scoped lang="scss">
.fileImage {
  display: flex;
}

.my-custom-confirm>>>.el-dialog {
  background-color: #f8d7da !important;
  /* 设置背景色 */
  border-color: #f5c6cb !important;
  /* 设置边框颜色 */
}


.bankLabelStyle {
  display: flex;
  margin: 8px;
}

.radioStyle {
  button {
    display: block;
    margin: 5px;
  }

  ::v-deep .el-checkbox__label {
    display: none !important;
  }

  ::v-deep .el-form-item__content {
    .ql-toolbar {
      display: none;
    }

    .ql-snow {
      border-top: 1px solid #ccc;
    }
  }
}

/* 禁止点击，但保持选中样式 */
.non-clickable-checkbox {
  pointer-events: none;
}

/* 保持复选框已选中时的样式不变 */
.non-clickable-checkbox .el-checkbox__input.is-checked {
  background-color: #409EFF;
  /* 选中时背景色 */
  border-color: #409EFF;
  /* 选中时边框色 */
  color: white;
  /* 选中时文字颜色 */
}

/* 使复选框状态保持选中样式 */
.non-clickable-checkbox.el-checkbox--is-checked .el-checkbox__inner {
  background-color: #409EFF !important;
  /* 确保选中时的背景色 */
  border-color: #409EFF !important;
}

/* 保持选中复选框时不改变外观 */
.non-clickable-checkbox.is-checked .el-checkbox__input {
  background-color: #409EFF;
  border-color: #409EFF;
}

::v-deep .el-radio__original {
  display: none !important;
  /* 隐藏原生 radio 输入，但仍然允许交互 */
}

::v-deep.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
  box-shadow: none !important;
}

.inforClass {
  font-size: 16px;
  font-weight: 700;
  display: flex;
  align-items: center;
}

.inforClass::before {
  content: '';
  width: 5px;
  height: 25px;
  background-color: #419eff;
  margin-right: 10px;
  display: inline-block;
}

.dialogClass {
  ::v-deep .el-dialog__body {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }
}
::v-deep p {
  margin: 0 !important;
}
</style>
